using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class MobileJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
    public Image joystickBase;
    public Image joystickThumb;
    public Vector3 inputVector;

    void Start()
    {
        joystickBase = GetComponent<Image>();
        joystickThumb = transform.GetChild(0).GetComponent<Image>();
    }

    public virtual void OnDrag(PointerEventData ped)
    {
        Vector2 pos;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBase.rectTransform, ped.position, ped.pressEventCamera, out pos))
        {
            pos.x = (pos.x / joystickBase.rectTransform.sizeDelta.x);
            pos.y = (pos.y / joystickBase.rectTransform.sizeDelta.y);

            inputVector = new Vector3(pos.x * 2 - 1, 0, pos.y * 2 - 1);
            inputVector = (inputVector.magnitude > 1.0f)? inputVector.normalized : inputVector;

            joystickThumb.rectTransform.anchoredPosition = new Vector3(inputVector.x * (joystickBase.rectTransform.sizeDelta.x / 2),
                                                                       inputVector.z * (joystickBase.rectTransform.sizeDelta.y / 2));
        }
    }

    public virtual void OnPointerDown(PointerEventData ped)
    {
        OnDrag(ped);
    }

    public virtual void OnPointerUp(PointerEventData ped)
    {
        inputVector = Vector3.zero;
        joystickThumb.rectTransform.anchoredPosition = Vector3.zero;
    }

    public Vector3 GetInputVector()
    {
        return inputVector;
    }
}